package xyz.hubery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import xyz.hubery.domain.UserAddress;
import xyz.hubery.model.R;
import xyz.hubery.service.UserAddressService;

import java.util.List;
import java.util.Random;

@RestController
@Api(tags = "用户钱包地址")
@RequestMapping("/userAddress")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService ;
    @GetMapping
    @ApiOperation(value = "查阅用户的钱包地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId" ,value = "用户的 Id"),
            @ApiImplicitParam(name = "current" ,value = "当前页") ,
            @ApiImplicitParam(name = "size" ,value = "每页显示的条数")
    })
    public R<Page<UserAddress>> findByPage(@ApiIgnore Page<UserAddress> page , Long userId){
        page.addOrder(OrderItem.desc("last_update_time")) ;
        Page<UserAddress> userAddressPage = userAddressService.page(page,new LambdaQueryWrapper<UserAddress>().eq(userId!=null,UserAddress::getUserId,userId)) ;
        return R.ok(userAddressPage) ;
    }


    @GetMapping("/getCoinAddress/{coinId}")
    @ApiOperation("查询用户的充币钱包地址")
    public R<String> getCoinAddress(@PathVariable Long coinId){
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        List<UserAddress> userAddressList = userAddressService.getUserAddressByCoinId(userId,coinId);
        if(CollectionUtils.isEmpty(userAddressList)) {
            return null;
        }
        Random random = new Random();
        int i = random.nextInt(userAddressList.size());
        return R.ok(userAddressList.get(i-1).getAddress());
    }
}
